# coding=utf-8
import redis
from django.conf import settings


class Redis(object):

    def __init__(self):
        self.redis = redis.Redis(
            connection_pool=redis.ConnectionPool(
                max_connections=100, **settings.REDIS_CONF))

    @staticmethod
    def instance():
        if not hasattr(Redis, "_instance"):
            Redis._instance = Redis()
        try:
            Redis._instance.r.ping()
        except Exception as e:
            Redis._instance = Redis()
        return Redis._instance


class WordHandWriteF(object):

    def __init__(self):
        self.redis = Redis.instance().redis
        self.key_pre = 'hw'

    def add_f(self, user_id):
        key = '{0}{1}'.format(self.key_pre, user_id)
        f = self.redis.incr(key)
        if f == 1:
            self.redis.expire(key, 30)
        return f


class WordStroke(object):

    def __init__(self):
        self.redis = Redis.instance().redis
        self.key_pre = 'ws'

    def set(self, txt, n):
        key = '{0}{1}'.format(self.key_pre, txt)
        self.redis.set(key, n)
        self.redis.expire(key, 60 * 3)

    def get(self, txt):
        key = '{0}{1}'.format(self.key_pre, txt)
        n = self.redis.get(key)
        if n:
            return int(n)
        return 0
